﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Windows.Forms;
using static BW.Mes.WinForms.BasicData.MaterialForm;
using System.Threading.Tasks;

namespace BW.Mes.WinForms.BasicData
{
    public partial class AddProductForm : XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _apiBaseUrl = "https://localhost:7274";

        public AddProductForm()
        {
            InitializeComponent();
            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (req, cert, chain, errors) => true
            };
            _httpClient = new HttpClient(handler);
            this.Load += AddProductForm_Load;
        }

        private async void AddProductForm_Load(object sender, EventArgs e)
        {
            comboBoxEditUnit.Properties.Items.AddRange(new string[] { "毫米", "厘米", "米", "克", "千克", "个", "次数", "小时" });
            comboBoxEditUnit.Properties.NullText = "请选择单位";
            await LoadMaterialGroups();
        }

        private async Task LoadMaterialGroups()
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_apiBaseUrl}/api/Material/GetMaterial");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);
                if (jsonObject["pageDatas"] != null)
                {
                    string dataJson = jsonObject["pageDatas"].ToString();
                    var groups = JsonConvert.DeserializeObject<List<MaterialModel>>(dataJson);

                    lookUpEditGroup.Properties.DataSource = groups;
                    lookUpEditGroup.Properties.DisplayMember = "MaterialName";
                    lookUpEditGroup.Properties.ValueMember = "Id";
                    lookUpEditGroup.Properties.NullText = "请选择物料群组";
                    lookUpEditGroup.Properties.Columns.Clear();
                    lookUpEditGroup.Properties.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("MaterialName", "物料名称"));
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载物料群组失败: {ex.Message}", "错误");
            }
        }

        private async void btnOK_Click(object sender, EventArgs e)
        {
            if (lookUpEditGroup.EditValue == null)
            {
                XtraMessageBox.Show("请选择一个物料群组。");
                return;
            }
            if (string.IsNullOrWhiteSpace(comboBoxEditUnit.Text))
            {
                XtraMessageBox.Show("请选择单位。");
                return;
            }
            var selectedGroup = lookUpEditGroup.GetSelectedDataRow() as MaterialModel;
            var model = new
            {
                ProductCode = textEditCode.Text,
                ProductName = textEditName.Text,
                Specification = textEditSpec.Text,
                Unit = comboBoxEditUnit.Text,
                Warning = int.TryParse(textEditWarning.Text, out int w) ? w : 0,
                MaterialId = (long)lookUpEditGroup.EditValue,
                MaterialType = selectedGroup != null ? selectedGroup.MaterialType : "",
                ProductMsg = textEditMsg.Text,
                CreatedBy = "wyj"
            };
            try
            {
                var json = JsonConvert.SerializeObject(model);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync($"{_apiBaseUrl}/api/Product/AddProduct", content);
                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("添加成功！");
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show($"添加失败：{response.ReasonPhrase} - {errorContent}");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"提交数据时出错: {ex.Message}", "错误");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void lookUpEditGroup_EditValueChanged(object sender, EventArgs e)
        {

        }
    }
}